package com.ruoyi.memoryleak;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/oom/2")
public class OOMController1 {

    // 静态集合：模拟一个所谓的“缓存”，它是GC Root，永远不会被回收
    private static final List<Object> LEAKY_STATIC_CACHE = new ArrayList<>();

    /**
     * 模拟内存泄漏接口
     * 调用方式: http://localhost:8080/leak?size=5
     *
     * @param size 每次请求向内存泄漏多少MB
     */
    @GetMapping("/leak")
    public String leakMemory(@RequestParam int size) {
        // 1. 每次请求分配 size MB 的内存
        byte[] memoryChunk = new byte[size * 1024 * 1024];
        // 2. 将其放入静态集合，导致GC无法回收
        LEAKY_STATIC_CACHE.add(memoryChunk);

        // 3. 返回当前状态
        return "SUCCESS: Added " + size + " MB to cache. Total held: " +
                (LEAKY_STATIC_CACHE.stream().mapToInt(b -> ((byte[]) b).length).sum() / (1024 * 1024)) + " MB";
    }
}